//
// Created by 14141 on 2024/7/21.
//
#include "led.h"
#include <osapi.h>
#include <user_interface.h>
// Create a timer
static os_timer_t ledTimer;
int isLedOpen = 0;
int flashTimes = 0;

void openLed()
{
    GPIO_OUTPUT_SET(2, 0);
    isLedOpen = 1;
}

void closeLed()
{
    GPIO_OUTPUT_SET(2, 1);
    isLedOpen = 0;
}

// Timer callback function
void ICACHE_FLASH_ATTR led_timer_callback(void *arg) {
    if (isLedOpen) {
        closeLed();
        if (flashTimes > 0) {
            flashTimes--;
            if (flashTimes == 0) {
                os_timer_disarm(&ledTimer);
            }
        }
    } else {
        openLed();
    }
}

//times为-1，一直闪。为具体的数字，亮起，熄灭算是一次，达到次数后停止闪。
void ICACHE_FLASH_ATTR beginFlash(int times)
{
    flashTimes = times;
    os_timer_disarm(&ledTimer);
    os_timer_setfn(&ledTimer, (os_timer_func_t *)led_timer_callback, NULL);
    os_timer_arm(&ledTimer, 500, 1); //定时器重复
}

void ICACHE_FLASH_ATTR stopFlash() {
    os_timer_disarm(&ledTimer);
    closeLed();
}


